package system

import base.Bank
import base.Branch
import base.Dimensions

/**
 * 用户实体类  --执行 s2-quickstart base StaffMember  Authority    自动生成后改动
 */
class StaffMember implements Serializable {

    private static final long serialVersionUID = 1
    transient springSecurityService

    /*登录的用户名*/
    String username
    /*登录密码,以密文形式存放*/
    String password
   /*用户是否启用     ,默认启用*/
    boolean enabled = true
    /*登录账号是否过期,默认不过期*/
    boolean accountExpired
    /*登录账号 是否锁定,默认不锁定*/
    boolean accountLocked
    /*登录密码是否过期,默认不过期*/
    boolean passwordExpired

    //activiti  need
    String id
    String firstName = "first"
    String lastName = "last"
    String email = "12@126.com"
    Date dateCreated//创建时间
    Date lastUpdated//最后更新的时间

    // 下面是据项目自己填的
    /*用户姓名*/
    String realname
    Department department


    /*开户银行*/
    Bank bank
    /*开户支行*/
    Branch branch
    /*银行账号*/
    String bankAccount
    /*开 户 名*/
    String accountName
    /*用户职级 父类编号为 002*/
    Dimensions rank
    /*手机号码*/
    String phoneNum
    /*员工编码*/
    String  code
    /*微信UserId*/
    String wxId
    /*钉钉UserId*/
    String ddId
    /*是否离职*/
    Boolean dimission=false

    static transients = ['name', 'role']
    static hasMany = [staffMemberRole: StaffMemberRole]
    static constraints = {
        username blank: false, unique: true, nullable: true
        password blank: false, nullable: true
        department nullable: true
        realname nullable: true
        dateCreated nullable: true
        lastUpdated nullable: true
        firstName blank: false
        lastName blank: false
        email email: true, blank: false
        bank nullable: true
        branch nullable: true
        bankAccount nullable: true
        accountName nullable: true
        phoneNum nullable: true
        code nullable: true
        wxId nullable: true
        ddId nullable: true
        dimission nullable: true
    }

    String getName() {
        return realname
    }

    List<Role> getRole() {
        return StaffMemberRole.findAllByStaffMember(this).role //this.staffMemberRole?.role
    }
    static mapping = {
        password column: 'password'
        id generator: 'uuid'
        enabled sqlType: 'int'
        accountExpired sqlType: 'int'
        accountLocked sqlType: 'int'
        passwordExpired sqlType: 'int'

    }

    Set<Authority> getAuthorities() {                    //得到用户的所有权限列表
        StaffMemberAuthority.findAllByStaffMember(this).collect { it.authority } as Set
    }

    def beforeInsert() {         //新增用户时,保存到数据库前自动对密码加密
        password = springSecurityService.encodePassword(password)

    }
    //
    def beforeUpdate() {
        if (isDirty(password)) {
            password = springSecurityService.encodePassword(password)
        }

    }
    //2012-2-15 fang add 为用户 添加角色 ,同时添加角色下的所有权限
    boolean addRole(Long roleId) {
        Role role = Role.get(roleId)
        if (role) {
            if (StaffMemberRole.create(role, this, true)) {
                def authoritys = RoleAuthority.getAuthoritys(role).collect { it } as Set//得到该角色下的所有权限
                println("add authoritys " + authoritys?.toString())
                StaffMemberAuthority.createManyAuthoritys(this, authoritys)
                true
            } else {
                this.errors.each {
                    log.error(it)
                }
                false
            }
        } else {
            log.error("角色" + roleId + "不存在")
            false
        }
    }
    /**
     * 删除 某一用户与角色 的关联
     * 1.解除 该用户与 该角色的关联
     * 2. 解除该用户 关联的所有权限
     * 3.添加用户与 已关联角色对应的权限  的关联
     */
    def delRole = { role ->
        // Role role=Role.get(roleId)
        if (role) {
            StaffMemberRole.remove(role, this, true)//删除角色

            //  def authoritys=RoleAuthority.getAuthoritys(role) //得到该角色下的所有权限
            def otherRoles = this.role.flatten() - [role]//该用户的其他角色
            //删除该用户的关联的全部权限
            StaffMemberAuthority.removeAll(this)
            //添加上 该用户其他 角色对应的权限
            def temList = []
            otherRoles.each {
                temList << it
            }
            temList.each {
                Set<Authority> authoritySet = Role.getAuthoritys(it).collectAll { au -> au } as Set
                StaffMemberAuthority.createManyAuthoritys(this, authoritySet, true)
            }

        }

    }
    //2012-2-15 fang add 删除与用户关联的权限
    void delAuthoritys() {
        StaffMemberAuthority.removeAll(this)//删除与用户关联的权限
    }

    String toString() {
        "$realname"
    }

    transient utilsService

    def buildDomain() {
        def b = [:] + this.properties
        b.remove('status')
        b.remove('department')
        def param = [allowformat: true]
        b = utilsService.truncProp(this, b, param) { amap ->
            amap << ['id': this.id]
            amap << ['department': this.department?.name]
        }
        b
    }

    def buildDomainList(list) {
        def rds = []
        list.each {
            def b = [:] + it.properties
            b.remove('status')
            def param = [allowformat: true]
            b = utilsService.truncProp(it, b, param) { amap ->
                amap << ['id': it.id]
                amap << ['department': it.department?.name]
            }
            rds << b
        }
        return rds
    }
}

